package com.atguigu.gulimall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * 注入这个Bean就能修改序列化器，改为用Json格式序列化，用JSON的好处是他简单易读并且能跨平台
     * 为什么注入这个Bean就能修改序列化器？
     * CacheAutoConfiguration -> CacheConfigurationImportSelector方法中getConfigurationClass
     * -> mappings.put(CacheType.REDIS, RedisCacheConfiguration.class);
     * ->找到RedisCacheConfiguration
     * ->determineConfiguration中，没有redisCacheConfiguration才用默认的，如果有则用这个
     * * @Bean方法中的参数都会从Spring的容器中自动注入
     * 因此只要往容器中加入RedisCacheConfiguration对象，RedisCacheConfiguration的determineConfiguration()方法中就能用
     * @param cacheProperties
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeValuesWith
                (RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));

        /**
         * 这里是仿照RedisCacheConfiguration的determineConfiguration()方法中的写法，把配置文件中内容也读入并使之生效
         * 这里的关键是cacheProperties，容器中并没有，因此需要使用@EnableConfigurationProperties(CacheProperties.class)把它加入到容器中
         * 然后在方法参数中写上就行了，因为@Bean标记的方法的参数会自动从容器中注入
         */
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }
}
